import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:my_shop/util/logs.dart';
import 'package:logger/logger.dart';

/// created by devin
/// 2025/5/10 23:29
/// description: 
class HttpLogInterceptor extends InterceptorsWrapper {

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    _logRequest(options);
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    _logResponse(response);
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    _logError(err);
    super.onError(err, handler);
  }

  /// 记录请求日志
  void _logRequest(RequestOptions options) {
    printLog('----------Request Start----------');
    printLog('URL: ${options.baseUrl}${options.path}');
    printLog('Method: ${options.method}');
    printLog('Headers: ${options.headers}');
    printLog('Data: ${options.data}');
    printLog('Query Parameters: ${options.queryParameters}');
  }

  /// 记录响应日志
  void _logResponse(Response response) {
    printLog('----------Response Start----------');
    printLog('Status Code: ${response.statusCode}');
    // 如果 response.data 是一个 Map
    if (response.data is Map) {
      // 将 Map 转换为格式化的 JSON 字符串
      String formattedJson = JsonEncoder.withIndent('  ').convert(response.data);
      printLog('Data: $formattedJson');
    } else if (response.data is String) {
      // 如果 response.data 是 JSON 字符串，先解析再格式化
      try {
        Map<String, dynamic> dataMap = jsonDecode(response.data);
        String formattedJson = JsonEncoder.withIndent('  ').convert(dataMap);
        printLog('Data: $formattedJson');
      } catch (e) {
        // 如果不是 JSON 字符串，直接打印
        printLog('Data: ${response.data}');
      }
    } else {
      // 其他类型直接打印
      printLog('Data: ${response.data}');
    }
  }

  /// 记录错误日志
  void _logError(DioException error) {
    printLog('----------Error Start----------', Level.error);
    printLog('Error Type: ${error.type}', Level.error);
    printLog('Error Message: ${error.message}', Level.error);
    printLog('Error Response: ${error.response?.data}', Level.error);
  }
}